import pandas as pd
import os
import sys

# Analytics Parms 编码器
class AnalyticsParamsCoder:

    #const fileds
    PARAMS_FILE_PATH = '../../Iteration/VersionHolder/Generated/analytics/AnalyticsParams.cs'
    CLASS_HEAD = "public static class {0}_{1}_params\n"
    CLASS_FILED = "\tpublic const {0} _{1} = {2};   //{3}"
    OBJECT_ELEMENT_HEAD = "public class {0}_{1}\n"
    OBJECT_ELEMENT_FIELD = "\tpublic {0} {1};  //{2}"
    DEFINE_HEAD = "public static class AnalyticsEventDefine\n{\n"
    EVENT_FIELD_DEFINE_SIGN = '\tpublic const string {0}_event_name = "{0}";'

    #field
    _lvEventNameArr = ["g_level_start", "g_revive", "g_level_win", "g_level_fail", "g_level_quit"]
    _lvCommonObjectParmsArr = ["g_o_star_times", "g_model_detail", "g_o_return_level", "g_o_purchase_level", "g_o_used_item", "g_bar_detail", "g_o_collect_detail"]

    # construction
    def __init__(self):
         self._defineBuilder = ''
         self._strBuilder = ''


    # function
    def GenerateSingleParmsClass(self, event_name, filed_type_list, field_name_list, filed_explain_list):
        object_group_dic = {}
        content_str_list = []
        list_count = len(filed_type_list)
        for index in range(0, list_count):
            field_type = filed_type_list[index]
            field_name = field_name_list[index]
            field_explain = filed_explain_list[index]

            # 填充对象组数据
            if field_type == '对象组':
                continue
            else:
                if self.IsObjectGroupElement(field_name):
                    object_group = [event_name, field_type, field_name, field_explain]
                    name_arr = field_name.split('.')
                    if name_arr[0] in object_group_dic:
                        object_group_dic[name_arr[0]].append(object_group)
                    else:
                        object_group_dic[name_arr[0]] = [object_group]

            # 处理非对象组数据
            if self.IsNeedGenerateExplainStruct(event_name, field_explain):
                field_explain = field_explain.replace('\n', '')
                format_name = field_name.replace("._", "_")
                content_str = self.CLASS_HEAD.format(event_name, format_name)
                content_str += '{\n'
                arr = field_explain.split(';')
                parse_filed_type = self.ParseFiledType(field_type)
                for item in arr:
                    if item == '':
                        continue
                    detail_arr = item.split(':')
                    item_value = detail_arr[0]
                    if parse_filed_type == 'string':
                        item_value = f'"{item_value}"'

                    content_str += self.CLASS_FILED.format(parse_filed_type, detail_arr[0], item_value, detail_arr[1])
                    content_str += '\n'
                content_str += '}\n'
                content_str_list.append(content_str)
            else:
                continue

        # 处理对象组数据
        if len(object_group_dic) > 0:
            for arr in object_group_dic.values():
                object_group_str_list = self.GenerateObjectGroupStr(arr)
                if object_group_str_list:
                    for object_group_str in object_group_str_list:
                        content_str_list.append(object_group_str)

        return content_str_list


    # 是否需要生成属性说明类
    def IsNeedGenerateExplainStruct(self, event_name, explain):
        if pd.isna(explain):
             return False

        arr = explain.split(';')
        arr_count = len(arr)
        if arr_count == 0:
            return False
        else:
            if arr_count == 1:
                detail_arr = arr[0].split(':')
                detail_arr_count = len(detail_arr)
                if detail_arr_count != 2:
                    return False
            else:
                return True
        return True


    # 是否是对象组结构
    def IsObjectGroupElement(self, field_name):
         arr = field_name.split('.')
         arr_count = len(arr)
         if arr_count == 2:
              return True
         else:
              return False


    # 解析字段类型
    def ParseFiledType(self, t):
            if t == '字符串':
                return 'string'
            if t == '数值':
                return 'int'
            if t == '布尔':
                return 'bool'
            if t == '列表':
                return 'string'
            raise ValueError(f'{t} is out of range')


    # 处理对象组数据
    def GenerateObjectGroupStr(self, arr):
        event_name = arr[0][0]
        field_class_name = arr[0][2].split('.')[0]

        if event_name in self._lvEventNameArr and field_class_name in self._lvCommonObjectParmsArr:
            return

        content_str = self.OBJECT_ELEMENT_HEAD.format(event_name, field_class_name)
        content_str += '{'

        group_list = []
        for item in arr:
            content_str += '\n'
            field_type = item[1]
            field_name = item[2]
            field_explain = item[3]
            # 可能为float类型？
            if isinstance(field_explain, str):
                field_explain = field_explain.replace("\n", " ")
            name_arr = field_name.split('.')
            parse_filed_type = self.ParseFiledType(field_type)
            content_str += self.OBJECT_ELEMENT_FIELD.format(parse_filed_type, name_arr[1], field_explain)

        content_str += "\n}\n"
        group_list.append(content_str)
        return group_list

    # 创建所有事件名集合类
    def GenerateEventDefineText(self, event_name_arr):
        self._defineBuilder = self.DEFINE_HEAD
        arr_count = len(event_name_arr)
        for index in range(0, arr_count):
            item = event_name_arr[index]
            self._defineBuilder += self.EVENT_FIELD_DEFINE_SIGN.format(item)
            if index < arr_count - 1:
                self._defineBuilder += '\n'
        self._defineBuilder += '\n}'


    # 拼接整个params文本
    def SaveAllParams(self, params_str_arr, version):
        count = len(params_str_arr)
        for index in range(0, count):
            single_str = params_str_arr[index]
            self._strBuilder += f"{single_str}"
            self._strBuilder += '\n'

        # 填充EventDefine内容
        self._strBuilder += self._defineBuilder

        # 路径替换正确的版本
        self.PARAMS_FILE_PATH = self.PARAMS_FILE_PATH.replace("VersionHolder", version)
        self.PARAMS_FILE_PATH = os.path.abspath(self.PARAMS_FILE_PATH)

        # 确保目录存在
        target_dir = os.path.dirname(self.PARAMS_FILE_PATH)
        if not os.path.exists(target_dir):
                os.makedirs(target_dir, exist_ok=True)  # 递归创建目录

        with open(self.PARAMS_FILE_PATH, 'w') as f:
                f.write(self._strBuilder)
        print(f"### {self.PARAMS_FILE_PATH} write success !!!")